
package org.finegold.core.delivery;


import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.ECLP.EclpOpenService.response.createWbOrder.CoCreateLwbResultForCreateWbOrder;
import com.jd.open.api.sdk.request.ECLP.*;
import com.jd.open.api.sdk.response.ECLP.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.finegold.core.delivery.entity.SendDelivery;
import org.finegold.core.delivery.entity.TokenResult;
import org.finegold.core.delivery.entity.UpdateDelivery;
import org.finegold.core.delivery.props.DeliveryProperties;
import org.finegold.core.http.util.HttpUtil;
import org.finegold.core.tool.api.R;
import org.finegold.core.tool.jackson.JsonUtil;
import org.finegold.core.tool.utils.BeanUtil;
import org.finegold.core.tool.utils.Func;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 京东下单类
 *
 * @author QinXueFeng
 */

@Slf4j
public class JdDeliveryTemplate implements DeliveryTemplate {

	private  DeliveryProperties deliveryProperties;

	private  JdClient jdClient;

	public JdDeliveryTemplate(DeliveryProperties deliveryProperties, JdClient jdClient){
		this.jdClient=jdClient;
		this.deliveryProperties=deliveryProperties;
	}

	public TokenResult getTokenByCode(String code) {
		String json = HttpUtil.get(deliveryProperties.getArgs().getStr("token-url")+"&app_key="+deliveryProperties.getAppKey()+"&app_secret="+deliveryProperties.getAppSecret()+"&code="+code,null);
		TokenResult parse = JsonUtil.parse(json, TokenResult.class);
		return parse;
	}
	public TokenResult  getTokenByRefresh(String refreshToken) {
		String json = HttpUtil.get(deliveryProperties.getArgs().getStr("refresh-token-url")+"&app_key="+deliveryProperties.getAppKey()+"&app_secret="+deliveryProperties.getAppSecret()+"&refresh_token="+refreshToken,null);
		TokenResult parse = JsonUtil.parse(json, TokenResult.class);
		return parse;
	}
	@SneakyThrows
	@Override
	public <T> R addDeliveryOrder(T data) {
		SendDelivery sendDelivery = BeanUtil.copy(data, SendDelivery.class);
		LocalDateTime now = LocalDateTime.now();
		EclpCoCreateWbOrderRequest request = BeanUtil.copy(data, EclpCoCreateWbOrderRequest.class);
		request.setDeptNo(sendDelivery.getIsInProvince()==0?deliveryProperties.getProvinceOutDeptNo():deliveryProperties.getProvinceInDeptNo());
		request.setSignReceiptFlag(Byte.valueOf("1"));
		request.setDeliveryReceiptFlag(Byte.valueOf("1"));
		request.setCreateTime(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		request.setTemptureNum(Byte.valueOf(sendDelivery.getTemptureNum()));
		request.setPickupBeginTime(LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).concat(" 18:00:00"));
		request.setPickupEndTime(LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).concat(" 21:00:00"));
		//25 特快重货 6:特快零担
		request.setDeliveryType(Byte.valueOf("6"));
		EclpCoCreateWbOrderResponse response = jdClient.execute(request);
		log.info("request==={}",JsonUtil.toJson(request));
		log.info("EclpCoCreateWbOrderResponse==={}",response.getMsg());
		CoCreateLwbResultForCreateWbOrder coCreateLwbResultResult = response.getCoCreateLwbResultResult();
		if(1!=coCreateLwbResultResult.getResultCode()){
			return R.fail(coCreateLwbResultResult.getResultMsg());
		}
		return R.data(coCreateLwbResultResult);
	}

	@SneakyThrows
	@Override
	public <T> R updateOrder(T data) {
		UpdateDelivery updateDelivery = BeanUtil.copy(data, UpdateDelivery.class);
		EclpCoUpdateB2BSWbMainExpressItemQtyRequest request = BeanUtil.copy(data, EclpCoUpdateB2BSWbMainExpressItemQtyRequest.class);
		request.setDeptNo(updateDelivery.getIsInProvince()==0?deliveryProperties.getProvinceOutDeptNo():deliveryProperties.getProvinceInDeptNo());
		request.setNewWBType(2);
		EclpCoUpdateB2BSWbMainExpressItemQtyResponse response = jdClient.execute(request);
		log.info("request==={}",JsonUtil.toJson(request));
		log.info("EclpCoCreateWbOrderResponse==={}",response.getMsg());
		return R.data(response.getResult().getResultMessage());
	}
	@SneakyThrows
	@Override
	public <T> R cancelOrder(T data) {
		UpdateDelivery updateDelivery = BeanUtil.copy(data, UpdateDelivery.class);
		EclpCoCancelWaybillRequest request = BeanUtil.copy(data, EclpCoCancelWaybillRequest.class);
		request.setDeptNo(updateDelivery.getIsInProvince()==0?deliveryProperties.getProvinceOutDeptNo():deliveryProperties.getProvinceInDeptNo());
		request.setCancelMode(0);
		EclpCoCancelWaybillResponse response = jdClient.execute(request);
		log.info("request==={}",JsonUtil.toJson(request));
		log.info("EclpCoCreateWbOrderResponse==={}",response.getMsg());
		return R.data(response.getCancelWaybillResult().getMessage());
	}

	@SneakyThrows
	@Override
	public <T> R getRouteService(T data) {
		UpdateDelivery updateDelivery = BeanUtil.copy(data, UpdateDelivery.class);
		EclpCoGotoB2BSWbMainAllTrackRequest request = BeanUtil.copy(data, EclpCoGotoB2BSWbMainAllTrackRequest.class);
		request.setDeptNo(updateDelivery.getIsInProvince()==0?deliveryProperties.getProvinceOutDeptNo():deliveryProperties.getProvinceInDeptNo());
		request.setNewWBType(2);
		EclpCoGotoB2BSWbMainAllTrackResponse response = jdClient.execute(request);
		log.info("request==={}",JsonUtil.toJson(request));
		log.info("EclpCoCreateWbOrderResponse==={}",response.getMsg());
		return R.data(response.getCoCreateLwbResultResult().getB2bLwbTrack());
	}

	@SneakyThrows
	@Override
	public <T> R<String> generateOrder(T data) {
		UpdateDelivery updateDelivery = BeanUtil.copy(data, UpdateDelivery.class);
		EclpCoGenerateBdWayBillFileRequest request = BeanUtil.copy(data, EclpCoGenerateBdWayBillFileRequest.class);
		request.setDeptNo(updateDelivery.getIsInProvince()==0?deliveryProperties.getProvinceOutDeptNo():deliveryProperties.getProvinceInDeptNo());
		request.setNewWBType(2);
		EclpCoGenerateBdWayBillFileResponse response = jdClient.execute(request);
		log.info("request==={}",JsonUtil.toJson(request));
		log.info("getMsg==={}",response.getMsg());
		log.info("getResult==={}",response.getResult());
		String json = response.getResult().getContent();
		if(Func.isNotEmpty(json)&&!json.contains("https")&&!json.contains("http")){
			json="https:"+json;
		}
		return R.data(json);
	}

	@SneakyThrows
	@Override
	public <T> R receiptFlagPhoto(T data) {
		EclpCoGetReceiptFlagPhotoRequest request = BeanUtil.copy(data, EclpCoGetReceiptFlagPhotoRequest.class);
		EclpCoGetReceiptFlagPhotoResponse response=jdClient.execute(request);
		return R.data(response.getCoCreateLwbResultResult().getListPhoto());
	}

//	@SneakyThrows
//	public static void main(String[] args) {
//		JdClient client=new DefaultJdClient("https://api.jd.com/routerjson","24683505eccf4bf387ded60cd96c26dd2odm","19F76255E936B2D77A13E0FE6E058ECF","0b76621a7515454ba401703b4d0dfc9a");
//		String s = JsonUtil.toJson(new SendDelivery());
//		System.out.println(s);
//		EclpCoCreateWbOrderRequest request=new EclpCoCreateWbOrderRequest();
//
//		request.setDeptNo("EBU4418054805891");
//		request.setSignReceiptFlag(Byte.valueOf("1"));
//		request.setDeliveryReceiptFlag(Byte.valueOf("1"));
//		request.setSenderName("高升");
//		request.setSenderMobile("18636971023");
//		request.setSenderAddress("山西省晋中市祁县经济开发区晋商大道22号（5层、6层）");
//
//		request.setReceiverName("小雨");
//		request.setReceiverMobile("13245678909");
//		request.setReceiverAddress("北京大兴区南海家园六里32-1-1701");
//		request.setExpressItemQty(1);
//		request.setOrderNo("1234567890123456");
//		request.setRemark("订单备注");
//
//		request.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//		request.setCreateUser("山西复盛公键康药业有限公司");
//		request.setExpressItemName("药品");
//		request.setSenderCompany("山西复盛公键康药业有限公司");
//		request.setTemptureNum(Byte.valueOf("4"));
//		//25 特快重货 6:特快零担
//		request.setDeliveryType(Byte.valueOf("6"));
//		EclpCoCreateWbOrderResponse response=client.execute(request);
//		System.out.println(response.getMsg());
		//----------------------------------------取消------------------------
//		EclpCoCancelWaybillRequest request=new EclpCoCancelWaybillRequest();
//		request.setDeptNo("EBU4418054805891");
//		request.setLwbNo("JDVA07093727474");
//		request.setReason("客户通知取消运单");
//		request.setCancelMode(0);
//		EclpCoCancelWaybillResponse response=client.execute(request);
//		System.out.println(response);
		//---------------------------------------修改------------------------
//		EclpCoUpdateB2BSWbMainExpressItemQtyRequest request=new EclpCoUpdateB2BSWbMainExpressItemQtyRequest();
//		request.setDeptNo("EBU4418054805891");
//		request.setNewWBType(2);
//		request.setNo("JDVA07105055280");
//		request.setExpressItemQty(30);
//		//request.setExtendFieldStr("{'miniBox':'1','middleBox':'2'}");
//		String s=client.executeToString(request);
//		System.out.println(s);

		//---------------------------------------物流信息--------------------------
//		EclpCoGotoB2BSWbMainAllTrackRequest request=new EclpCoGotoB2BSWbMainAllTrackRequest();
//		request.setDeptNo("EBU4418054805891");
//		request.setNewWBType(2);
//		request.setNo("JDVA07093727474");
//		EclpCoGotoB2BSWbMainAllTrackResponse response = client.execute(request);
//		String json = JsonUtil.toJson(response.getCoCreateLwbResultResult());
//		System.out.println(json);
		//-------------------------------------面单打印-------------------------
//		EclpCoGenerateBdWayBillFileRequest request=new EclpCoGenerateBdWayBillFileRequest();
//		request.setDeptNo("EBU4418054805891");
//		request.setNewWBType(2);
//		request.setNo("JDVA07103682590");
//		EclpCoGenerateBdWayBillFileResponse response=client.execute(request);
//		System.out.println(response.getResult().getContent());
//		EclpCoGetReceiptFlagPhotoRequest request=new EclpCoGetReceiptFlagPhotoRequest();
//		request.setLwbNo("JDVA07103682590");
//		EclpCoGetReceiptFlagPhotoResponse response=client.execute(request);
//		System.out.println(response);
//	}
}
